import 'dart:io';

import 'package:extended_image/extended_image.dart';
import 'package:flustars/flustars.dart';

import 'package:flutter/material.dart';

import 'package:get/get.dart';
import 'package:zrjz/comm/base/base.dart';
import 'package:zrjz/comm/widget/my_load_image.dart';
import 'package:zrjz/comm/widget/my_text_view.dart';
import 'package:zrjz/generated/assets.dart';

import '../../router/page_router.dart';
import '../constants/color_constants.dart';
import 'common_widget.dart';

/// 预览的图片的PageView
class PreviewPhotoPage extends BaseStatefulPage {
  PreviewPhotoPage({super.key});

  //启动当前页面
  static Future<T?>? startInstance<T>(List<String> imgs, int position) {
    return Get.toNamed(RouterPath.PREVIEW_IMAGE, arguments: {'imgs': imgs, "position": position});
  }

  @override
  _PreviewPhotoPageState createState() => _PreviewPhotoPageState();

  @override
  GetxController createRawController() {
    throw UnimplementedError();
  }
}

class _PreviewPhotoPageState extends State<PreviewPhotoPage> {
  late List<String> images;
  int currentIndex = 0;

  @override
  void initState() {
    super.initState();
    images = Get.arguments['imgs'];
    currentIndex = Get.arguments['position'];
  }

  @override
  void dispose() {
    super.dispose();
    clearGestureDetailsCache();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        backgroundColor: ColorConstants.black,
        // appBar: CommonWidget.appBar(context, "Preview"),
        body: SafeArea(
          bottom: true,
          top: false,
          //真正的 Content 布局
          child: Column(
            children: [
              CommonWidget.rowHeight(height: ScreenUtil.getStatusBarH(context)),
              Row(
                children: [
                  //间距
                  CommonWidget.rowWidth(width: 30),
                  Expanded(
                    child: MyTextView(
                      "${currentIndex + 1}/${images.length}",
                      textColor: ColorConstants.white,
                      fontSize: 18,
                      isFontRegular: true,
                      textAlign: TextAlign.center,
                    ),
                  ),

                  InkWell(
                    onTap: () {
                      Get.back();
                    },
                    child: const MyAssetImage(
                      Assets.imagesDialogDeleteIcon,
                      width: 14,
                      height: 14,
                    ),
                  ),

                  //间距
                  CommonWidget.rowWidth(width: 15),
                ],
              ),
              Expanded(
                  child: ExtendedImageGesturePageView.builder(
                controller: ExtendedPageController(
                  //图片PageView的配置选项
                  initialPage: currentIndex,
                  pageSpacing: 10,
                ),
                preloadPagesCount: 2,
                itemCount: images.length,
                scrollDirection: Axis.horizontal,
                onPageChanged: (int index) {
                  setState(() {
                    currentIndex = index;
                  });
                },
                itemBuilder: (BuildContext context, int index) {
                  //默认网络加载的占位图
                  final Widget placeholder = Container(
                    //如果没有设置占位图，使用默认的灰色背景内置Icon小图标
                    width: double.infinity,
                    height: double.infinity,
                    color: ColorConstants.greye0,
                    alignment: Alignment.center,
                    child: const MyAssetImage(
                      Assets.imagesImgDefaultPlaceholder,
                      width: 40,
                      height: 39,
                    ),
                  );

                  //区分网络图片和本地图片
                  Widget image = images[index].startsWith("http")
                      ? ExtendedImage.network(
                          images[index],
                          fit: BoxFit.contain,
                          timeLimit: const Duration(milliseconds: 30000),
                          cache: true,
                          mode: ExtendedImageMode.gesture,
                          loadStateChanged: (ExtendedImageState state) {
                            switch (state.extendedImageLoadState) {
                              case LoadState.loading:
                                return placeholder;

                              case LoadState.completed:
                                return null;

                              case LoadState.failed:
                                return placeholder;
                            }
                          },
                          initGestureConfigHandler: (ExtendedImageState state) {
                            return GestureConfig(
                              // 图片展示的配置选项
                              inPageView: true,
                              initialScale: 1.0,
                              maxScale: 5.0,
                              animationMaxScale: 6.0,
                              initialAlignment: InitialAlignment.center,
                              cacheGesture: false,
                            );
                          },
                        )
                      : ExtendedImage.file(
                          File(images[index]),
                          fit: BoxFit.contain,
                          mode: ExtendedImageMode.gesture,
                          initGestureConfigHandler: (ExtendedImageState state) {
                            return GestureConfig(
                              // 图片展示的配置选项
                              inPageView: true,
                              initialScale: 1.0,
                              maxScale: 5.0,
                              animationMaxScale: 6.0,
                              initialAlignment: InitialAlignment.center,
                              cacheGesture: false,
                            );
                          },
                        );

                  if (index == currentIndex) {
                    return Hero(
                      // tag: index.toString(),
                      tag: "0",
                      child: image,
                    );
                  } else {
                    return image;
                  }
                },
              )),
            ],
          ),
        ));
  }
}
